home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C23 / Wrapped.cpp < prev   
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.5 KB  |  72 lines

  1. //: C23:Wrapped.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Safe, atomic pointers
  7. #include <fstream>
  8. #include <cstdlib>
  9. using namespace std;
  10. ofstream out("wrapped.out");
  11.  
  12. // Simplified. Yours may have other arguments.
  13. template<class T, int sz = 1> class PWrap {
  14.   T* ptr;
  15. public:
  16.   class RangeError {}; // Exception class
  17.   PWrap() {
  18.     ptr = new T[sz];
  19.     out << "PWrap constructor" << endl;
  20.   }
  21.   ~PWrap() {
  22.     delete []ptr;
  23.     out << "PWrap destructor" << endl;
  24.   }
  25.   T& operator[](int i) throw(RangeError) {
  26.     if(i >= 0 && i < sz) return ptr[i];
  27.     throw RangeError();
  28.   }
  29. };
  30.  
  31. class Cat {
  32. public:
  33.   Cat() { out << "Cat()" << endl; }
  34.   ~Cat() { out << "~Cat()" << endl; }
  35.   void g() {}
  36. };
  37.  
  38. class Dog {
  39. public:
  40.   void* operator new[](size_t sz) {
  41.     out << "allocating an Dog" << endl;
  42.     throw int(47);
  43.   }
  44.   void operator delete[](void* p) {
  45.     out << "deallocating an Dog" << endl;
  46.     ::delete p;
  47.   }
  48. };
  49.  
  50. class UseResources {
  51.   PWrap<Cat, 3> Bonk;
  52.   PWrap<Dog> Og;
  53. public:
  54.   UseResources() : Bonk(), Og() {
  55.     out << "UseResources()" << endl;
  56.   }
  57.   ~UseResources() {
  58.     out << "~UseResources()" << endl;
  59.   }
  60.   void f() { Bonk[1].g(); }
  61. };
  62.  
  63. int main() {
  64.   try {
  65.     UseResources ur;
  66.   } catch(int) {
  67.     out << "inside handler" << endl;
  68.   } catch(...) {
  69.     out << "inside catch(...)" << endl;
  70.   }
  71. } ///:~
  72.